import axios from 'axios'
import { ApiException } from '@/utils/exception/api-exception.ts'
import { useUserStore } from '@/stores/userStore.ts'

const server = axios.create({
  timeout: 10000,
})

server.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token !== null) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

server.interceptors.response.use(
  response => {
    if (response.data.code !== 200) {
      return Promise.reject(new ApiException(response.data.msg, response.data.code))
    }
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

export default server
